package com.wordlearning.app.controller;

import com.wordlearning.app.entity.VoiceSetting;
import com.wordlearning.app.service.VoiceSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/voice-settings")
public class VoiceSettingController {

    private final VoiceSettingService voiceSettingService;

    @Autowired
    public VoiceSettingController(VoiceSettingService voiceSettingService) {
        this.voiceSettingService = voiceSettingService;
    }

    @PostMapping
    public ResponseEntity<VoiceSetting> createVoiceSetting(@RequestBody VoiceSetting voiceSetting) {
        try {
            VoiceSetting createdVoiceSetting = voiceSettingService.createVoiceSetting(voiceSetting);
            return new ResponseEntity<>(createdVoiceSetting, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<VoiceSetting> getVoiceSettingById(@PathVariable("id") Long id) {
        return voiceSettingService.getVoiceSettingById(id)
                .map(voiceSetting -> new ResponseEntity<>(voiceSetting, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<VoiceSetting> getVoiceSettingByUserId(@PathVariable("userId") Long userId) {
        VoiceSetting voiceSetting = voiceSettingService.getOrCreateDefaultVoiceSetting(userId);
        return new ResponseEntity<>(voiceSetting, HttpStatus.OK);
    }

    @PutMapping("/{id}")
    public ResponseEntity<VoiceSetting> updateVoiceSetting(@PathVariable("id") Long id, @RequestBody VoiceSetting voiceSetting) {
        try {
            VoiceSetting updatedVoiceSetting = voiceSettingService.updateVoiceSetting(id, voiceSetting);
            return new ResponseEntity<>(updatedVoiceSetting, HttpStatus.OK);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<HttpStatus> deleteVoiceSetting(@PathVariable("id") Long id) {
        try {
            voiceSettingService.deleteVoiceSetting(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

}